package com.qiyu.dubbo.router.starter.zone.router;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Router;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义的一个router组件: 基于zone参数进行不同版本选择的一个router组件
 *
 * @author linhao
 * @date created in 5:11 下午 2020/11/21
 */
@Slf4j
public class ZoneVersionSelectRouter implements Router {

    @Override
    public URL getUrl() {
        return null;
    }

    @Override
    public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        //每次请求都会被切入到这个route模块
        String consumerBranch = System.getProperty("git.branch");
        log.info(this.getRouterName() + " consumerBranch is {} ", consumerBranch);
        Invoker providerInvoker = null;
        for (Invoker<T> invoker : invokers) {
            String providerBranch = invoker.getUrl().getParameter("git.branch");
            if (StringUtils.isEmpty(providerBranch)) {
                providerInvoker = invoker;
            } else if (providerBranch.equals(consumerBranch)) {
                log.info(this.getRouterName() + " providerVersion matched was {} ", providerBranch);
                return invokers;
            }
        }
        log.info(this.getRouterName() + " providerVersion matched  default version ");
        return Arrays.asList(providerInvoker);
    }

    @Override
    public boolean isRuntime() {
        return false;
    }

    @Override
    public boolean isForce() {
        return false;
    }

    @Override
    public int getPriority() {
        return -100;
    }

    private String getRouterName() {
        return " ====== ZoneVersionSelectRouter ====== ";
    }


}
